package cn.frank.framework.caesar.module.ai.qwen.rest;

import cn.frank.framework.caesar.module.ai.qwen.conf.arrangement.assistant.AssistantUnique;
import dev.langchain4j.service.TokenStream;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.extensions.Extension;
import io.swagger.v3.oas.annotations.extensions.ExtensionProperty;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * @description: TODO
 * @author: renjiangyang
 * @date 2025/6/7 14:43:51
 * @since 1.8
 */
@Tag(name = "3 会话-独立记忆", description = "session", extensions = {
        @Extension(properties = {@ExtensionProperty(name = "x-order", value = "3", parseValue = true)}
        )
})
@RestController
@RequestMapping("/ai/openAiMemory2")
public class QwenChatMemory2RestController extends BaseQwenRestController {

    @Autowired
    AssistantUnique assistantUnique;

    @Operation(summary = "提问")
    @Parameters({
            @Parameter(name = "userId", description = "", required = true, in = ParameterIn.QUERY),
            @Parameter(name = "message", description = "", required = true, in = ParameterIn.QUERY)
    })
    @GetMapping(value = "/chat")
    public String chat(@RequestParam(name = "userId", defaultValue = "1") Integer userId,
                       @RequestParam(name = "message", defaultValue = "你是谁") String message) {
        return assistantUnique.chat(userId, message);
    }

    @Operation(summary = "流式")
    @GetMapping(value = "/stream", produces = "text/stream;charset=UTF-8")
    public Flux<String> memoryStreamChat(@RequestParam(name = "userId", defaultValue = "1") Integer userId,
                                         @RequestParam(name = "message", defaultValue = "你是谁") String message,
                                         HttpServletResponse response) {
        TokenStream stream = assistantUnique.stream(userId, message);
        return Flux.create(sink -> {
            stream.onPartialResponse(s -> {
                        System.out.println("s = " + s);
                        sink.next(s);
                    })
                    .onCompleteResponse(c -> {
                        System.out.println(" 结束 ");
                        sink.complete();
                    })
                    .onError(sink::error)
                    .start();

        });
    }

}
